// extension的Tab页
var jointTemplate = Vue.component('joint-Template', {
    template: readComponentHTML("jointTemplate"),
    props: {
        path: {
            type: String
        }
    },
    data() {
        return {
            ruleForm: {
                templateCode: '',
                jsCode: '',
                links: '',
                extendJson: '',
                configs: [],
                path:''
                // exports: '',
                // functions: ''
            },
            tableData: [{
                field: '',
                value: '',
                isBool: false,
                isNew: false
            }],
            isEdit: false,
            isSubmit: false,
            compile: false,
            resp: '',
            rules: {
            },
            jsCodeEditor: null,
            linkEditor: null,
            codeEditor: null,
            customTemplateSearch: []
        }
    },
    mounted() {
        this.ruleForm.path = this.path;
        this.jsCodeEditor = this.initCodeEdit("jsCode", "230px", "text/javascript");
        this.linkEditor = this.initCodeEdit("link", "120px", "shell", true, true);
        this.codeEditor = this.initCodeEdit("code", "230px", "shell", true, true);
        this.init();
    },
    methods: {
        getCodeEditOptions(mode, customTips) {
            var options = {
                lineNumbers: false, // 是否开启行号
                indentWithTabs: true,
                styleActiveLine: true, // 选中行高亮
                mode: mode,
                matchBrackets: true,
                tabSize: 2,
                hintOptions: {
                    completeSingle: false,
                    // hint: this.handleShowHint,
                },
            };
            if (customTips) {
                options.hintOptions["hint"] =  this.handleShowHint;
            }
            return options;
        },
        initCodeEdit(id, height, mode, customTips, readOnly) {
            var editor = CodeMirror.fromTextArea(document.getElementById(this.path + id), this.getCodeEditOptions(mode, customTips));
            editor.setSize('auto',height);
            // 代码提示功能 当用户有输入时，显示提示信息
            editor.on("inputRead", (cm) => {
                cm.showHint();
            });
            if (readOnly) {
                editor.setOption("readOnly",true)
                editor.setOption("cursorBlinkRate",-1)
            }
            return editor;
        },
        init(){
            var that = this;
            axios.get('/simpledevelop/template/joint/load?path=' + this.path).then(function (resp) {
                var data = resp.data.data;
                that.resp = resp.data.desc;
                that.ruleForm.links = data.links;
                that.ruleForm.templateCode = data.templateCode;
                that.ruleForm.extendJson = data.params;
                that.ruleForm.jsCode = data.jsCode;
                that.jsCodeEditor.setValue(data.jsCode);
                that.linkEditor.setValue(data.links);
                that.codeEditor.setValue(data.templateCode);
            });
        },
        resetForm() {
            this.ruleForm.extendJson = '';
            this.isEdit = false;
            this.compile = true;
            this.changeReadOnly(this.linkEditor, true);
            this.changeReadOnly(this.codeEditor, true);
            this.init();
        },
        changeisLocation(e) {
            this.isLocation = e;
        },
        addNewRow(index) {
            var lastIndex = null;
            if (index.target) {
                lastIndex = this.tableData.length - 1;
            } else if ((index + 1) == this.tableData.length) {
                lastIndex = index;
            }
            if (lastIndex != null) {
                if (this.tableData[lastIndex].field) {
                    this.tableData.push({
                        field: '',
                        value: '',
                        isBool: false,
                        isNew: true
                    })
                } else {
                    this.$message({
                        message: '上一行字段名不为空才可以新增一行',
                        type: 'warning'
                    })
                }
            }
        },
        fieldKeyUp(index, event) {
            switch (event.keyCode) {
                case 13:
                    this.addNewRow(index);
                    break;
                case 46:
                    this.delRow(index);
                    break;
            }
        },
        delRow(index) {
            if (this.tableData.length == 1) {
                this.$message({
                    message: '请至少保留一行数据',
                    type: 'warning'
                })
                return;
            }
            if (!this.tableData[index].isNew) {
                this.$message({
                    message: '默认参数不可删除',
                    type: 'warning'
                })
                return;
            }
            this.tableData.splice(index, 1);
        },
        initTable(newValue) {
            if (this.isSubmit) {
                return;
            }
            this.tableData = [];
            if (!newValue) {
                this.tableData = [{
                    field: '',
                    value: '',
                    isBool: false,
                }];
            }
            let split = newValue.split("|");
            for (let i = 0; i < split.length; i++) {
                this.tableData.push({
                    field: split[i],
                    value: '',
                    isBool: false,
                })
            }
        },
        addTooltip(h, {column, $index}) {
            var that = this;
            return [
                column.label,
                h(
                    'el-tooltip',
                    {
                        props: {
                            content: '在输入框回车、双击[新建]Delete[删除]', // 鼠标悬停时要展示的文字提示
                            placement: 'top' // 悬停内容展示的位置
                        }
                    },
                    [h('span', {class: {'el-icon-question': true}})] // 图标
                ),
                h(
                    'el-tooltip',
                    {
                        props: {
                            content: '点击刷新模板参数', // 鼠标悬停时要展示的文字提示
                            placement: 'top' // 悬停内容展示的位置
                        }
                    },
                    [h('span', {
                        class: {'el-icon-refresh': true},
                        on: {
                            // 更新模板字段
                            click: function () {
                                that.updateLink();
                            }
                        }
                    })] // 图标
                )
            ]
        },
        changeReadOnly(editor, readOnly) {
            editor.setOption("readOnly",readOnly);
            editor.setOption("cursorBlinkRate",readOnly ? -1 : 530);
        },
        edit(){
            this.isEdit = true;
            this.changeReadOnly(this.linkEditor, false);
            this.changeReadOnly(this.codeEditor, false);
            this.resp = "";
            this.compile = false;
            var that = this;
            if (that.customTemplateSearch.length == 0) {
                axios.get('/simpledevelop/template/joint/get/customs').then(function (resp) {
                    var data = resp.data.data;
                    for(var index in data) {
                        that.customTemplateSearch.push({
                            text: data[index].path,
                            displayText: data[index].name,
                            displayInfo: "自定义模板 " + data[index].path + ".js"
                        })
                    }
                });
            }
        },
        async updateLink(){
            this.getEditValue()
            var that = this;
            await axios.post(
                '/simpledevelop/template/joint/update',
                JSON.stringify(this.ruleForm),
                {headers: {'Content-Type': 'application/json'}})
                .then(function (response) {
                    that.ruleForm.extendJson = response.data.data;
                })
                .catch(error => this.$message.error(JSON.stringify(error)));
        },
        async compileScript(){
            await this.updateLink();
            var that = this;
            that.resp = "";
            this.isSubmit = true;
            var tmp = {};
            for (let i = 0; i < this.tableData.length; i++) {
                tmp[this.tableData[i].field] = this.tableData[i].isBool ? Boolean(this.tableData[i].value) : this.tableData[i].value;
            }
            this.ruleForm.extendJson = JSON.stringify(tmp);
            await axios.post(
                        '/simpledevelop/template/joint/compile',
                        JSON.stringify(this.ruleForm),
                        {headers: {'Content-Type': 'application/json'}})
                    .then(function (response) {
                        that.isSubmit = false;
                        that.resp = response.data.desc;
                        that.compile = response.data.reasonCode == 2000;
                        if (!that.compile) {
                            that.$message.error("编译未通过");
                            return;
                        }
                        that.$message.success("编译通过");
                    })
                    .catch(error => this.$message.error(JSON.stringify(error)));
        },
        async save() {
            await this.compileScript();
            if (!this.compile) {
                return;
            }
            var that = this;
            axios
                .post(
                    '/simpledevelop/template/joint/save',
                    JSON.stringify(this.ruleForm),
                    {headers: {'Content-Type': 'application/json'}})
                .then(function (response) {
                    that.$message.success("保存成功");
                    that.isEdit = false;
                    that.init();
                    that.changeReadOnly(that.linkEditor, true);
                    that.changeReadOnly(that.codeEditor, true);
                })
                .catch(error => this.$message.error(JSON.stringify(error)));

        },
        run(){
            this.getEditValue()
            var that = this;
            that.resp = "";
            this.isSubmit = true;
            var tmp = {};
            for (let i = 0; i < this.tableData.length; i++) {
                tmp[this.tableData[i].field] = this.tableData[i].isBool ? Boolean(this.tableData[i].value) : this.tableData[i].value;
            }
            this.ruleForm.extendJson = JSON.stringify(tmp);
            axios
                .post(
                    '/simpledevelop/template/joint/run',
                    JSON.stringify(this.ruleForm),
                    {headers: {'Content-Type': 'application/json'}})
                .then(function (response) {
                    that.isSubmit = false;
                    that.resp = response.data.desc;
                    if (response.data.reasonCode == 2000) {
                        that.$message.success("运行联合脚本成功");
                    }
                })
                .catch(error => this.$message.error(JSON.stringify(error)));
        },
        getEditValue() {
            this.ruleForm.jsCode = this.jsCodeEditor.getValue();
            this.ruleForm.templateCode = this.codeEditor.getValue();
            this.ruleForm.links = this.linkEditor.getValue();
        },
        hintRender(element, self, data) {
            let div = document.createElement("div");
            div.setAttribute("class", "autocomplete-div");

            let divText = document.createElement("div");
            divText.setAttribute("class", "autocomplete-name");
            divText.innerText = data.displayText;
            div.appendChild(divText);
            if (data.displayInfo) {
                let divInfo = document.createElement("div");
                divInfo.setAttribute("class", "autocomplete-hint");
                divInfo.innerText = data.displayInfo;
                div.appendChild(divInfo);
            }
            element.appendChild(div);
        },
        handleShowHint(cmInstance, hintOptions) {
            var that = this;
            let cursor = cmInstance.getCursor();
            let cursorLine = cmInstance.getLine(cursor.line);
            let end = cursor.ch;
            let start = end;
            let token = cmInstance.getTokenAt(cursor);
            var tips = [{
                text: "Link ;",
                displayText: "Link",
                displayInfo: "引用自定义模板"
            }, {
                text: "Function ;",
                displayText: "Function",
                displayInfo: "调用自定义函数"
            }, {
                text: "Export = ;",
                displayText: "Export",
                displayInfo: "暴露参数"
            }, {
                text: "<#switch >\r\n<#case >\r\n\r\n<#break>\r\n<#default>\r\n\r\n</#switch>",
                displayText: "<#switch",
                displayInfo: "freemarker switch"
            }, {
                text: "<#case >\r\n<#break>",
                displayText: "<#case",
                displayInfo: "freemarker case"
            }, {
                text: "<#break>",
                displayText: "<#break",
                displayInfo: "freemarker break"
            }, {
                text: "<#default>",
                displayText: "<#default",
                displayInfo: "freemarker default"
            }, {
                text: "<#if >\r\n</#if>",
                displayText: "<#if",
                displayInfo: "freemarker if"
            }, {
                text: "<#list as >\r\n</#list>",
                displayText: "<#list",
                displayInfo: "freemarker list"
            }, {
                text: "<#assign  = >",
                displayText: "<#assign",
                displayInfo: "freemarker assign"
            }, {
                text: "${ }",
                displayText: "$",
                displayInfo: "freemarker 取变量"
            }, {
                text: "createDir( )",
                displayText: "createDir",
                displayInfo: "创建目录(path)"
            }, {
                text: "createFile( , )",
                displayText: "createFile",
                displayInfo: "创建文件(path,fileName)"
            }, {
                text: "createFile( , , )",
                displayText: "createFile",
                displayInfo: "按照指定模板创建文件(path,fileName,modulePath)"
            }, {
                text: "createFileAppend( , , , )",
                displayText: "createFileAppend",
                displayInfo: "按照指定模板创建文件是否拼接(path,fileName,modulePath,isAppend)"
            }]
            tips.push(...that.customTemplateSearch);
            tips = tips.filter((data) => {
                data["render"] = that.hintRender;
                var text = data.displayText.toLowerCase();
                var search = token.string.toLowerCase();
                return text.indexOf(search) != -1
            })
            console.log(cmInstance, cursor + "123", cursorLine, end, token);
            return {
                list: tips,
                from: {
                    ch: token.start,
                    line: cursor.line
                },
                to: {
                    ch: token.end,
                    line: cursor.line
                }
            };
        },
    },
    computed: {
        listenExtendJson() {
            return this.ruleForm.extendJson;
        }
    },
    watch: {
        listenExtendJson: function (newValue, oldValue) {
            this.initTable(newValue);
        }
    }
})